package 
{
	import collisions.LinkedList;
	import collisions.QuadTree;
	import collisions.World;
	import enemies.Enemy;
	import flash.display.Sprite;
	import flash.events.Event;
	import graphics.GraphicsFactory;
	import graphics.Square;
	import player.Player;
	import renderers.EntityRenderer;
	import renderers.Renderer;
	
	/**
	 * ...
	 * @author Gareth Williams
	 */
	public class Main extends Sprite 
	{
		private var world:World = new World();
		private var display:Renderer;
		private var gamePad:Gamepad;
		private var goodGuy:Player;
		private var badGuys:Vector.<Enemy> = new Vector.<Enemy>(100, true);
		//private var allEntities:LinkedList = new LinkedList(null);
		
		public function Main():void 
		{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			// entry point
			
			//test----------------------------------------------------------------------------
				display = new EntityRenderer(this.stage);
				
				goodGuy = new Player(Constants.SCREEN_WIDTH / 2, Constants.SCREEN_HEIGHT / 2, 20);
				goodGuy.graphic = GraphicsFactory.createGraphic(
					GraphicsFactory.RED_SQUARE, goodGuy.radius, goodGuy.radius);
				gamePad = new Gamepad(this.stage);
				goodGuy.controller = gamePad;
				world.addBody(goodGuy);
				display.addRenderable(goodGuy);
				
				for (var i:int=0; i<badGuys.length; i++)
				{
					var badGuy:Enemy = new Enemy(Math.random() * Constants.SCREEN_WIDTH, Math.random() * Constants.SCREEN_HEIGHT);
					badGuy.graphic = GraphicsFactory.createGraphic(
						GraphicsFactory.BLUE_SQUARE, badGuy.radius, badGuy.radius);	
					world.addBody(badGuy);
					display.addRenderable(badGuy);
					badGuys[i] = badGuy;
				}
				
			//test----------------------------------------------------------------------------
			
			//main loop
			addEventListener(Event.ENTER_FRAME, this.main);
		}
		private function main(event:Event):void
		{
			gamePad.update();
			goodGuy.update();
			for each (var badGuy:Enemy in badGuys) badGuy.update(); 
			world.update();
			display.render();
			
			//debug
			//removeEventListener(Event.ENTER_FRAME, this.main);
		}
	}
}